{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
	.layui-form-item .layui-input-inline.end-time{
		float: none;
	}

	.goods_list .layui-table-body{max-height: 480px !important;}
	.forbidden{cursor:not-allowed;background-color: #eee;}
	.goods-title{display: flex;align-items: center;}
	.goods-title .goods-img{display: flex;align-items: center;justify-content: center;width: 55px;height: 55px;margin-right: 5px;}
	.goods-title .goods-img img{max-height: 100%;max-width: 100%;}
	.goods-title .goods-name{flex: 1;line-height: 1.6;}
</style>
{/block}
{block name="main"}
<div class="layui-form ns-form">
	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动名称：</label>
		<div class="layui-input-block">
			<input type="text" name="pintuan_name" value="{$pintuan_info.data.pintuan_name}" lay-verify="required" autocomplete="off" class="layui-input ns-len-long">
		</div>
		<div class="ns-word-aux">
			<p>活动名称将显示在活动列表中，方便商家管理</p>
		</div>
	</div>
	
	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动时间：</label>
		<div class="layui-inline">
			<div class="layui-input-inline ns-len-mid">
				<input type="text" id="start_time" name="start_time" lay-verify="required" class="layui-input" autocomplete="off" readonly>
				<i class="ns-calendar"></i>
			</div>
			<span class="layui-form-mid">-</span>
			<div class="layui-input-inline ns-len-mid end-time">
				<input type="text" id="end_time" name="end_time" lay-verify="required|time" class="layui-input" autocomplete="off" readonly>
				<i class="ns-calendar"></i>
			</div>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>参团人数：</label>
		<div class="layui-input-block">
			<input type="number" name="pintuan_num" value="{$pintuan_info.data.pintuan_num}" lay-verify="required|sum" autocomplete="off" class="layui-input ns-len-short">
		</div>
		<div class="ns-word-aux">
			<p>最少两人成团</p>
		</div>
	</div>
	
	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>拼团有效期：</label>
		<div class="layui-input-block">
			<div class="layui-input-inline ns-len-short">
				<select class="pintuan-day"></select>
			</div>
			<div class="layui-form-mid">日</div>
			<div class="layui-input-inline ns-len-short">
				<select class="pintuan-hour"></select>
			</div>
			<div class="layui-form-mid">时</div>
			<div class="layui-input-inline ns-len-short">
				<select class="pintuan-minute"></select>
			</div>
			<div class="layui-form-mid">分</div>
		</div>
		<div class="ns-word-aux">
			<p>提交订单后，在该时间范围内拼团成功才可购买</p>
		</div>
	</div>
	
	<div class="layui-form-item">
		<label class="layui-form-label">限制购买：</label>
		<div class="layui-input-block">
			<input type="number" name="buy_num" value="{$pintuan_info.data.buy_num}" lay-verify="num" autocomplete="off" class="layui-input ns-len-short">
		</div>
		<div class="ns-word-aux">
			<p>本次活动中一次最多可购买的商品数量</p>
		</div>
	</div>
	
	<div class="layui-form-item">
		<label class="layui-form-label">团长优惠：</label>
		<div class="layui-input-block">
			<input type="checkbox" name="is_promotion" {$pintuan_info.data.is_promotion == 1 ? 'checked' : ''} value="{$pintuan_info.data.is_promotion}" title="团长享受优惠价" lay-skin="primary" lay-filter="is_promotion">
		</div>
		<div class="ns-word-aux">
			<p>开启团长(开团人)优惠后，团长将享受更优惠价格，有助于提高开团率和成团率</p>
		</div>
	</div>

	<div class="layui-form-item goods_list">
		<label class="layui-form-label">活动商品：</label>
		<div class="layui-input-block">
			<table id="selected_goods_list" lay-filter="selected_goods_list"></table>
		</div>
	</div>
	
	<div class="layui-form-item">
		<label class="layui-form-label">是否单独购买：</label>
		<div class="layui-input-inline">
			<input type="radio" name="is_single_buy" value="1" title="是" {$pintuan_info.data.is_single_buy == 1 ? 'checked' : ''}>
			<input type="radio" name="is_single_buy" value="0" title="否" {$pintuan_info.data.is_single_buy == 0 ? 'checked' : ''}>
		</div>
	</div>
	
	<div class="layui-form-item">
		<label class="layui-form-label">是否虚拟成团：</label>
		<div class="layui-input-inline">
			<input type="radio" name="is_virtual_buy" value="1" title="是" {$pintuan_info.data.is_virtual_buy == 1 ? 'checked' : ''}>
			<input type="radio" name="is_virtual_buy" value="0" title="否" {$pintuan_info.data.is_virtual_buy == 0 ? 'checked' : ''}>
		</div>
	</div>
	
	<div class="layui-form-item layui-hide">
		<label class="layui-form-label">是否推荐：</label>
		<div class="layui-input-inline">
			<input type="radio" name="is_recommend" value="1" title="是" {$pintuan_info.data.is_recommend == 1 ? 'checked' : ''}>
			<input type="radio" name="is_recommend" value="0" title="否" {$pintuan_info.data.is_recommend == 0 ? 'checked' : ''}>
		</div>
	</div>
	
	<div class="layui-form-item layui-form-text">
		<label class="layui-form-label">备注：</label>
		<div class="layui-input-inline">
			<textarea name="remark" class="layui-textarea ns-len-long">{$pintuan_info.data.remark}</textarea>
		</div>
	</div>
	
	<div class="ns-form-row">
		<button class="layui-btn ns-bg-color" lay-submit lay-filter="save">保存</button>
		<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
	</div>
	
	<input type="hidden" name="pintuan_id" value="{$pintuan_info.data.pintuan_id}" />
	<input type="hidden" class="pintuan-time" value="{$pintuan_info.data.pintuan_time}" />
	<input type="hidden" name="goods_id" class="goods-id" value="{$pintuan_info.data.goods_id}" />
	<input type="hidden" name="is_virtual_goods" class="is-virtual-goods" value="{$pintuan_info.data.is_virtual_goods}" />
	<input type="hidden" class="start-time-pri" value="{$pintuan_info.data.start_time}" />
	<input type="hidden" class="end-time-pri" value="{$pintuan_info.data.end_time}" />
</div>
{/block}
{block name="script" }
<script type="text/html" id="toolbarOperation">
	<button class="layui-btn layui-btn-primary" lay-event="pintuan-price">拼团价格</button>
</script>
<script type="text/html" id="toolbarOperationOne">
	<button class="layui-btn layui-btn-primary" lay-event="pintuan-price">拼团价格</button>
	<button class="layui-btn layui-btn-primary" lay-event="pintuan-discounts-price">团长优惠价</button>
</script>
<script>
	var start_time_pri = ns.time_to_date($(".start-time-pri").val()),
		end_time_pri = ns.time_to_date($(".end-time-pri").val());
	var pintuan_time = $(".pintuan-time").val(), //总分钟数
		
		day_time = pintuan_time / (24 * 60), //天数
		houe_time = (pintuan_time % (24 * 60)) / 60, //小时
		second_time = (pintuan_time % (24 * 60)) % 60; //分钟

	var sku_list = [];
	sku_list = {:json_encode($pintuan_info.data.sku_list, JSON_UNESCAPED_UNICODE)};

	var pintuan_info = {:json_encode($pintuan_info.data,JSON_UNESCAPED_UNICODE)},is_promotion = 0;
	sku_list.forEach(function (item,index) {
		item.is_delete = item.pintuan_price ? 1 : 2;
	});

	var is_virtual = [];
	layui.use(['form', 'laydate'], function() {
		var form = layui.form,
			laydate = layui.laydate,
			repeat_flag = false,
			minDate = "";
		form.render();
		if(pintuan_info.is_promotion == 1){
			renderTableGroup(sku_list);
			is_promotion = 1;
		}else{
			renderTable(sku_list); // 初始化表格
			is_promotion = 0;
		}

		for (var i = 0; i <= 30; i++) {
			if (i < 10) {
				if (i == day_time) {
					var html = '<option value="' + i + '" selected>0' + i + '</option>';
				} else {
					var html = '<option value="' + i + '">0' + i + '</option>';
				}
			} else {
				if (i == day_time) {
					var html = '<option value="' + i + '" selected>' + i + '</option>';
				} else {
					var html = '<option value="' + i + '">' + i + '</option>';
				}
			}
			$(".pintuan-day").append(html);
		}
		for (var i = 0; i <= 23; i++) {
			if (i < 10) {
				if (i == houe_time) {
					var html = '<option value="' + i + '" selected>0' + i + '</option>';
				} else {
					var html = '<option value="' + i + '">0' + i + '</option>';
				}
			} else {
				if (i == houe_time) {
					var html = '<option value="' + i + '" selected>' + i + '</option>';
				} else {
					var html = '<option value="' + i + '">' + i + '</option>';
				}
			}
			$(".pintuan-hour").append(html);
		}
		for (var i = 0; i <= 59; i++) {
			if (i < 10) {
				if (i == second_time) {
					var html = '<option value="' + i + '" selected>0' + i + '</option>';
				} else {
					var html = '<option value="' + i + '">0' + i + '</option>';
				}
			} else {
				if (i == second_time) {
					var html = '<option value="' + i + '" selected>' + i + '</option>';
				} else {
					var html = '<option value="' + i + '">' + i + '</option>';
				}
			}
			$(".pintuan-minute").append(html);
		}
		form.render('select');
		
		//开始时间
		laydate.render({
			elem: '#start_time', //指定元素
			type: 'datetime',
			value: start_time_pri,
			done: function(value) {
				minDate = value;
				reRender();
			}
		});
		
		//结束时间
		laydate.render({
			elem: '#end_time', //指定元素
			type: 'datetime',
			value: end_time_pri
		});
		
		/**
		 * 重新渲染结束时间
		 * */
		function reRender() {
			$("#end_time").remove();
			$(".end-time").html('<input type="text" id="end_time" name="end_time" placeholder="请输入结束时间" lay-verify="required|time" class ="layui-input" autocomplete="off" readonly><i class="ns-calendar"></i> ');
			laydate.render({
				elem: '#end_time',
				type: 'datetime',
				min: minDate
			});
		}
		
		/**
		 * 表单验证
		 */
		form.verify({
			time: function(value) {
				var now_time = (new Date()).getTime();
				var start_time = (new Date($("#start_time").val())).getTime();
				var end_time = (new Date(value)).getTime();
				if (now_time > end_time) {
					return '结束时间不能小于当前时间!'
				}
				if (start_time > end_time) {
					return '结束时间不能小于开始时间!';
				}
			},
			num: function(value) {
				if (value < 1 || value % 1 != 0) {
					return '请输入大于0的正整数！';
				}
			},
			sum: function(value) {
				if (value < 2 || value % 1 != 0) {
					return '参团人数不能小于2，且必须是整数！';
				}
			},
			pintuan_price: function(value, item) {
				var price = $(item).parents("tr").find(".goods-price").text();
				if (Number(value) > Number(price)) {
					return '拼团价格不能大于商品价格';
				}
				if (value.trim() == "") {
					return '拼团价格不能为空';
				}
				if (Number(value) <= 0) {
					return '拼团价格必须大于0';
				}
				
				var arrMen = value.split(".");
				var val = 0;
				if (arrMen.length == 2) {
					val = arrMen[1];
				}
				if (val.length > 2) {
					return '拼团价格最多保留两位小数';
				}
			},
			promotion_price: function(value, item) {
				var price = $(item).parents("tr").find(".goods-price").text();
				if (Number(value) > Number(price)) {
					return '团长优惠价不能大于商品价格';
				}
				if (value.trim() == "") {
					return '团长优惠价不能为空';
				}
				if (Number(value) <= 0) {
					return '团长优惠价必须大于0';
				}
				
				var arrMen = value.split(".");
				var val = 0;
				if (arrMen.length == 2) {
					val = arrMen[1];
				}
				if (val.length > 2) {
					return '团长优惠价最多保留两位小数';
				}
			}
		});
		
		/**
		 * 监听团长优惠是否被选中
		 */
		form.on('checkbox(is_promotion)', function(data){
			if (data.elem.checked) {
				$(".ns-team-leader").removeClass("layui-hide");
				$(".ns-goods-null").attr("colspan", 4);
				$("input[name='is_promotion']").val(1);
				renderTableGroup(sku_list);
				is_promotion = 1;
			} else {
				$(".ns-team-leader").addClass("layui-hide");
				$(".ns-goods-null").attr("colspan", 3);
				$("input[name='is_promotion']").val(0);
				renderTable(sku_list);
				is_promotion = 0;
			}
		});
		
		form.on('submit(save)', function(data){
			data.field.sku_ids = [];
			data.field.goods_id = sku_list[0].goods_id;
			sku_list.forEach(function (item,index) {
				if (item.is_delete == 2) return false;
				data.field.sku_ids.push(item.sku_id);
			});
			if (data.field.sku_ids.length == 0) {
				layer.msg("请选择参与活动商品！", {icon: 5, anim: 6});
				return;
			}
			var skuLisArr = [];
			sku_list.forEach(function(item,index) {
				var sku_detail = {};
				sku_detail.sku_id = item.sku_id;
				sku_detail.goods_id = item.goods_id;
				sku_detail.pintuan_price = item.pintuan_price || 0;
				sku_detail.promotion_price = item.promotion_price || 0;
				sku_detail.is_delete = item.is_delete || 1;
				skuLisArr.push(sku_detail);
			});
			data.field.sku_list = skuLisArr;

			var day = $(".pintuan-day option:selected").text(),
				hour = $(".pintuan-hour option:selected").text(),
				minute = $(".pintuan-minute option:selected").text();
			
			var pintuan_time = Number(day) * 24 * 60 + Number(hour) * 60 + Number(minute);
			data.field.pintuan_time = pintuan_time;
			
			var time = new Date(data.field.end_time).getTime() - new Date(data.field.start_time).getTime();
			if (time < (pintuan_time * 60 * 1000)) {
				layer.msg("拼团有效期不能大于活动时长！", {icon: 5, anim: 6});
				return;
			}
			
			if (data.field.is_promotion == undefined) {
				data.field.is_promotion = 0;
			}

			// if(repeat_flag) return;
			// repeat_flag = true;
			
			$.ajax({
				type: 'POST',
				dataType: 'JSON',
				url: ns.url("pintuan://shop/pintuan/edit"),
				data: data.field,
				async: false,
				success: function(res){
					repeat_flag = false;
					
					if (res.code == 0) {
						layer.confirm('编辑成功', {
							title:'操作提示',
							btn: ['返回列表', '继续操作'],
							yes: function(){
								location.href = ns.url("pintuan://shop/pintuan/lists");
							}
						});
					}else{
						layer.msg(res.message);
					}
				}
			})
		});
	});

	// 表格渲染
	function renderTable(sku_list) {
		//展示已知数据
		table = new Table({
			elem: '#selected_goods_list',
			page:false,
			limit:Number.MAX_VALUE,
			cols: [
				[{
					width: "3%",
					type: 'checkbox',
					unresize: 'false'
				},{
					field: 'sku_name',
					title: '商品名称',
					width: '23%',
					unresize: 'false',
					templet: function(data) {
						var html = '';
						html += `
							<div class="goods-title">
								<div class="goods-img">
									<img layer-src src="${data.sku_image ? ns.img(data.sku_image) : ''}" alt="">
								</div>
								<p class="ns-multi-line-hiding goods-name" data-goods_id="${data.goods_id}" data-sku_id="${data.sku_id}" title="${data.sku_name}">${data.sku_name}</p>
							</div>
						`;
						return html;
					}
				}, {
					field: 'price',
					title: '商品价格',
					unresize: 'false',
					width: '15%',
					templet: function(data) {
						return '<p class="ns-line-hiding" title="'+ data.price +'">￥<span class="goods-price">' + data.price +'</span></p>';
					}
				}, {
					field: 'stock',
					title: '库存',
					unresize: 'false',
					width: '10%',
					templet: function(data) {
						return '<p class="stock">' + data.stock +'</p>';
					}
				}, {
					title: '拼团价格(元)',
					unresize: 'false',
					width: '13%',
					templet: '#pintuan_price'
				}, {
					title: '操作',
					toolbar: '#operation',
					width: '10%',
					unresize: 'false'
				}]
			],
			data: sku_list,
			toolbar: '#toolbarOperation'
		});
		/**
		 * 批量操作
		 */
		table.toolbar(function(obj) {

			if (obj.data.length < 1) {
				layer.msg('请选择要操作的数据');
				return;
			}
			switch (obj.event) {
				case "pintuan-price":
					editInput(0,obj);
					break;
				case "pintuan-discounts-price":
					editInput(1,obj);
					break;
			}
		});
	}
	// 团长优惠价表格渲染
	function renderTableGroup(sku_list) {

		//展示已知数据
		table = new Table({
			elem: '#selected_goods_list',
			page:false,
			limit:Number.MAX_VALUE,
			cols: [
				[{
					width: "3%",
					type: 'checkbox',
					unresize: 'false'
				},{
					field: 'sku_name',
					title: '商品名称',
					width: '23%',
					unresize: 'false',
					templet: function(data) {
						var html = '';
						html += `
							<div class="goods-title">
								<div class="goods-img">
									<img layer-src src="${data.sku_image ? ns.img(data.sku_image) : ''}" alt="">
								</div>
								<p class="ns-multi-line-hiding goods-name" data-goods_id="${data.goods_id}" data-sku_id="${data.sku_id}" title="${data.sku_name}">${data.sku_name}</p>
							</div>
						`;
						return html;
					}
				}, {
					field: 'price',
					title: '商品价格',
					unresize: 'false',
					width: '15%',
					templet: function(data) {
						return '<p class="ns-line-hiding" title="'+ data.price +'">￥<span class="goods-price">' + data.price +'</span></p>';
					}
				}, {
					field: 'stock',
					title: '库存',
					unresize: 'false',
					width: '10%',
					templet: function(data) {
						return '<p class="stock">' + data.stock +'</p>';
					}
				}, {
					title: '拼团价格(元)',
					unresize: 'false',
					width: '13%',
					templet: '#pintuan_price'
				}, {
					title: '团长优惠价(元)',
					unresize: 'false',
					width: '13%',
					templet: '#promotion_price'
				}, {
					title: '操作',
					toolbar: '#operation',
					width: '10%',
					unresize: 'false'
				}]
			],
			data: sku_list,
			toolbar: '#toolbarOperationOne'
		});
		/**
		 * 批量操作
		 */
		table.toolbar(function(obj) {

			if (obj.data.length < 1) {
				layer.msg('请选择要操作的数据');
				return;
			}
			switch (obj.event) {
				case "pintuan-price":
					editInput(0,obj);
					break;
				case "pintuan-discounts-price":
					editInput(1,obj);
					break;
			}
		});
	}
	function editInput(textIndex=0,data) {
		var text = [{
			name: '拼团价格',
			value: 'pintuan_price'
		},{
			name: '团长优惠价',
			value: 'promotion_price'
		}];

		layer.open({
			type: 1,
			title:"修改"+text[textIndex].name,
			area:['600px'],
			btn:["保存","返回"],
			content: `
			<div class="layui-form-item">
				<label class="layui-form-label"><span class="required">*</span>${text[textIndex].name}：</label>
				<div class="layui-input-block">
					<input type="text" name="bargain_edit_input" lay-verify="required" autocomplete="off" class="layui-input ns-len-mid" placeholder="请输入${text[textIndex].name}">
				</div>
			</div>
		`,
			yes: function(index, layero){
				var val = $("input[name='bargain_edit_input']").val();
				if (!val){
					layer.msg("请输入" + text[textIndex].name);
					return false;
				}
				data.data.forEach(function (item,index) {
					sku_list.forEach(function (skuItem,skuIndex) {
						if (item.sku_id == skuItem.sku_id){
							sku_list[skuIndex][text[textIndex].value] = val;
						}
					})
				});
				if (is_promotion == 1){
					renderTableGroup(sku_list);
				}else{
					renderTable(sku_list);
				}
				layer.closeAll();
			}
		});
	}


	function bargainPintuanPrice(index,event) {
		sku_list[index-1].pintuan_price = event.srcElement.value;
	}
	function bargainPromotionPrice(index,event) {
		sku_list[index-1].promotion_price = event.srcElement.value;
	}

	$("body").on("click",".no-participation",function(){
		$(this).text("设置参与");
		$(this).parents("tr").find("input").each(function (index,item) {
			$(item).attr("readonly",true);
			$(item).attr("disabled",true);
			$(item).addClass("forbidden");
			$(item).attr("lay-verify","");
		})

		// pintuan_price  promotion_price  lay-verify
		$(this).addClass("participation").removeClass("no-participation");
		sku_list[$(this).parents("tr").attr("data-index")].is_delete = 2;
	});

	$("body").on("click",".participation",function(){
		$(this).text("设置不参与");
		$(this).parents("tr").find("input").each(function (index,item) {
			$(item).attr("readonly",false);
			$(item).attr("disabled",false);
			$(item).removeClass("forbidden");
			if($(item).hasClass(".pintuan-price")){
				$(item).attr("lay-verify","pintuan_price");
			}else{
				$(item).attr("lay-verify","promotion_price");
			}
		});

		$(this).removeClass("participation").addClass("no-participation");
		sku_list[$(this).parents("tr").attr("data-index")].is_delete = 1;
	});

	function back() {
		location.href = ns.url("pintuan://shop/pintuan/lists");
	}
</script>

<script type="text/html" id="pintuan_price">
	{{# if(!d.pintuan_price){ }}
	<input type="number" class="layui-input ns-len-input pintuan-price forbidden" value="{{d.pintuan_price}}" min="0.00" oninput="bargainPintuanPrice({{ d.LAY_INDEX }},event)" onporpertychange="bargainPromotionPrice({{ d.LAY_INDEX }},event)" readonly disabled/>
	{{# }else{ }}
	<input type="number" class="layui-input ns-len-input pintuan-price" value="{{d.pintuan_price}}" lay-verify="pintuan_price" min="0.00" oninput="bargainPintuanPrice({{ d.LAY_INDEX }},event)" onporpertychange="bargainPromotionPrice({{ d.LAY_INDEX }},event)"/>
	{{# } }}
</script>

<script type="text/html" id="promotion_price">
	{{# if(!d.pintuan_price){ }}
	<input type="number" class="layui-input ns-len-input promotion-price forbidden" value="{{d.promotion_price}}" min="0.00" oninput="bargainPromotionPrice({{ d.LAY_INDEX }},event)" onporpertychange="bargainPromotionPrice({{ d.LAY_INDEX }},event)" readonly disabled/>
	{{# }else{ }}
	<input type="number" class="layui-input ns-len-input promotion-price" value="{{d.promotion_price}}" lay-verify="promotion_price" min="0.00" oninput="bargainPromotionPrice({{ d.LAY_INDEX }},event)" onporpertychange="bargainPromotionPrice({{ d.LAY_INDEX }},event)"/>
	{{# } }}
</script>

<script type="text/html" id="operation">
	<div class="ns-table-btn">
		{{# if(!d.pintuan_price){ }}
		<a class="layui-btn participation">设置参与</a>
		{{# }else{ }}
		<a class="layui-btn no-participation">设置不参与</a>
		{{# } }}
	</div>
</script>
{/block}